//
//  SearchProducts_Vm.swift
//  Pods
//
//  Created by eme on 2017/3/29.
//
//
import RxSwift
import NetWorkCore
import SwiftyJSON
import UtilCore
import RickonCore

/*
 owner:cy
 update:2017年01月03日09:38:56
 info: 商品搜索vm
 VC:   ProductDetail_Vc
 */
class SearchProducts_Vm :BaseList_Vm {
    /// 表示正在刷新中
    let loading = ActivityIndicator()
    /// 表示正在加载更多种..
    let loadingMore = ActivityIndicator()
    /*
     接收返回的数据
     */
    /// 返回首页数据
    let productsElements = Variable<[ProductlistModel]>([])
    
    let searchProductElement = PublishSubject<SearchProductModel>()
    /*
     设置参数
     */
    /// 第一次查询标志（1-是2-否）（第一次查询会返回品牌，类目，属性信息）
    var firistflag = 1
    /// 筛选参数修改
    let sx_Param = Variable<(brid:String,ptid:String,pavstr:String,minamount:String,maxamount:String,moq:String)>(brid:"",ptid:"",pavstr:"",minamount:"",maxamount:"",moq:"")
    /// 排序参数
    let orderType_Param = Variable<OrderType>(.zh_px)
    /// 关键字搜索
    let keyword_Param =  Variable<String>("")
    let vid_Param =  Variable<String>("")
    
    init(
        input: (
        refreshTriger: Observable<Void>,
        loadMoreTriger: Observable<Void>
        )
        ) {
        super.init()
        let keywordAndVidParam =  Observable.combineLatest(
            keyword_Param.asDriver().asObservable(),
            vid_Param.asDriver().asObservable()
        ){ $0}
            .map{ keyword , vid  -> (keyword:String,vid:String) in
                return (keyword,vid)
            }.shareReplay(1)
        let keywordAndSxParam = keywordAndVidParam
            .asObservable()
            .map{ keywordAndVid  -> (keyword:String,brid:String,ptid:String,pavstr:String,minamount:String,maxamount:String,moq:String,vid:String) in
                self.firistflag = 1
                let item = (keyword:keywordAndVid.keyword,brid:"",ptid:"",pavstr:"",minamount:"",maxamount:"",moq:"",vid:keywordAndVid.vid)
                return item
            }.skip(1)
        let sxParamAndKeyword = sx_Param
            .asObservable()
            .map{ sxParam -> (keyword:String,brid:String,ptid:String,pavstr:String,minamount:String,maxamount:String,moq:String,vid:String) in
                let item = (keyword:self.keyword_Param.value,brid:sxParam.brid,ptid:sxParam.ptid,pavstr:sxParam.pavstr,minamount:sxParam.minamount,maxamount:sxParam.maxamount,moq:sxParam.moq,vid:self.vid_Param.value)
                return item
            }.skip(1)
        let sxAndKeyword =  Observable
            .of(keywordAndSxParam,sxParamAndKeyword)
            .merge()
        /// 下拉刷新 商品数据列表
        let refreshRequest  = Observable
            .combineLatest(
                input.refreshTriger.map{ _ in return 0 },
                sxAndKeyword,
                orderType_Param.asDriver().asObservable()
            ){ $0}
            .map{ pageIndex, xsAndKeyword, orderType_Param  in
                return HomePageApi.seachproducts(keyword: xsAndKeyword.keyword, brid: xsAndKeyword.brid, ptid: xsAndKeyword.ptid, firistflag: "\(self.firistflag)", pavstr: xsAndKeyword.pavstr, oflag: orderType_Param.orderBy, minamount: xsAndKeyword.minamount, maxamount: xsAndKeyword.maxamount, moq: xsAndKeyword.moq, page: pageIndex, length: AppConfig.pageSize,vid: xsAndKeyword.vid)
            }
            .shareReplay(1)
        /// 下拉刷新发起网络请求
        let refreshResponse = refreshRequest
            .emeRequestApiForObj(SearchProductModel.self,activityIndicator: loading)
            .shareReplay(1)
        refreshResponse
            .subscribe(onNext: { [unowned self] (result) in
                switch result {
                case .success(let data):
                    /**
                     *  如果返回的数据正好相同 则默认还有数据
                     */
                    self.hasNextPage.value = data.productlist.count == AppConfig.pageSize
                    self.productsElements.value = data.productlist
                    if self.firistflag == 1{
                        ///第一次查询标志（1-是2-否）（第一次查询会返回品牌，类目，属性信息）
                        self.searchProductElement.onNext(data)
                    }
                    self.page = 1
                    self.firistflag = 2
                case .failure(let error):
                    self.error.onNext(error)
                }
            })
            .disposed(by: disposeBag)
        
        /// 发起加载更多事件源
        let loadMoreRequest = input.loadMoreTriger.map{_ in
            return HomePageApi.seachproducts(keyword: self.keyword_Param.value, brid: self.sx_Param.value.brid, ptid: self.sx_Param.value.ptid, firistflag: "\(self.firistflag)", pavstr: self.sx_Param.value.pavstr, oflag: self.orderType_Param.value.orderBy, minamount: self.sx_Param.value.minamount, maxamount: self.sx_Param.value.maxamount, moq: self.sx_Param.value.moq, page: self.page, length: AppConfig.pageSize,vid: self.vid_Param.value)
            }.shareReplay(1)
        /// 加载更多网络请求
        let loadMoreResponse = loadMoreRequest
            .emeRequestApiForObj(SearchProductModel.self)
            .shareReplay(1)
        loadMoreResponse
            .subscribe(onNext: {[unowned self] (result) in
                switch result {
                case .success(let data):
                    /**
                     *  如果返回的数据正好相同 则默认还有数据
                     */
                    self.hasNextPage.value = data.productlist.count == AppConfig.pageSize
                    // self.searchProductElement.onNext(data)
                    self.productsElements.value  += data.productlist
                    /**
                     *  需要修改page 页数
                     */
                    self.page += 1
                    
                case .failure(let error):
                    self.error.onNext(error)
                }
            })
            .disposed(by: disposeBag)
    }
}
